<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../conf/config.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Exchange\AMQPExchangeType;

$exchange = 'simple'; // 交换器名称
$queue = 'simple'; // 队列名称

try {
    $connection = new AMQPStreamConnection(HOST, PORT, USER, PASS, VHOST); // 建立连接到RabbitMQ服务器
    $channel = $connection->channel(); // 建立通道

    $channel->exchange_declare($exchange, AMQPExchangeType::DIRECT, false, false, false); // 试探性声明一个交换机
    $channel->queue_declare($queue, false, false, false, false); // 试探性声明一个队列
    $channel->queue_bind($queue, $exchange); // 队列通过路由键绑定交换器

    // 生产10条消息
    for ($i = 0; $i < 10; $i++) {
        $msgBody = "简单模式下生成第【" . ($i + 1) . "】条消息";
        $message = new AMQPMessage($msgBody, ['content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]);
        $channel->basic_publish($message, $exchange); // 队列绑定交换器
        echo ' [x] Sent ' . $msgBody . "\n";
        sleep(1);
    }
    $channel->close(); // 关闭通道
    $connection->close(); // 关闭连接
} catch (Exception $e) {
    die($e->getMessage());
}